package com.hundsun.fcp.widget;

import java.util.Timer;
import java.util.TimerTask;

import com.hundsun.fcp.R;

import android.content.Context;
import android.content.res.TypedArray;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;


public class TimerButton extends Button {
	
	private Timer mTimer;
	private int countNumDecrease;
	private int countNumIncrease;

	public TimerButton(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		init(attrs);
	}

	public TimerButton(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(attrs);
	}

	public TimerButton(Context context) {
		super(context);

	}
	private void init(AttributeSet attrs) {

		if (attrs != null) {
			TypedArray typedArrayed = getContext()
					.obtainStyledAttributes(attrs, R.styleable.TimerButton);
			countNumDecrease = typedArrayed.getInt(R.styleable.TimerButton_timecount, 60);
			countNumIncrease = 0;
			typedArrayed.recycle();
		}
		

	}
	
	public void onDestory(){
		clearStatus();
	}
	

	public void onTimerStart() {
		if(isEnabled()){
			setEnabled(false);
			setBackgroundResource(R.color.signup_msgcode_bg) ;
			mTimer = new Timer();
			mTimer.schedule(new TimerTask(){
				@Override
				public void run() {							
					countNumIncrease++;	
					countNumDecrease--;
					new Handler(Looper.getMainLooper()).post(new Runnable() {
							@Override
							public void run() {
								if(countNumIncrease == 60){
									clearStatus();
								}else{
									setText(String.format(getContext().getString(R.string.transfer_dxyamcode_dy), countNumDecrease));
								}
							}

															
						});											
				}
				
			}, 10,1000);
		}			
		
	}
	
	private void clearStatus() {
		if(mTimer != null){
			mTimer.cancel();
		}	
		setEnabled(true);
		mTimer = null;
		countNumIncrease = 0;
		countNumDecrease = 60;
		setText(getContext().getString(R.string.transfer_dxyamcode));
		setBackgroundResource(R.color.msgcode_bg) ;
	}	
	

}
